package com.osmino.contacts.icon;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ListView;
import com.osmino.contacts.R;
import com.osmino.contacts.entity.Group;
import com.osmino.core.AbsListActivity;

public final class ChooseIconActivity extends AbsListActivity implements OnClickListener {

	public static final String EXTRA_EXISTING_ICON = "com.osmino.contacts.intent.extra.EXISTING_ICON";
	public static final String EXTRA_PICKED_ICON = "com.osmino.contacts.intent.extra.PICKED_ICON";
	private GroupIconAdapter mAdapter;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.choose_icon_layout);
		mAdapter = new GroupIconAdapter(this);
		setListAdapter(mAdapter);
		getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		findViewById(R.id.positive_button).setOnClickListener(this);
		findViewById(R.id.negative_button).setOnClickListener(this);
		int currentResource = getIntent().getIntExtra(EXTRA_EXISTING_ICON, Group.ICON_DEFAULT);
		int size = mAdapter.getCount();
		for (int i = 0; i < size; i++) {
			Integer item = mAdapter.getItem(i);
			if (item == currentResource) {
				getListView().setItemChecked(i, true);
				break;
			}
		}
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		Log.e(getClass().toString(), "choice mode="+getListView().getChoiceMode());
	}
	
	@Override
	public void onBackPressed() {
		setResult(RESULT_CANCELED);
		super.onBackPressed();
	}

	@Override
	public void onClick(View view) {
		int viewId = view.getId();
		switch (viewId) {
			case R.id.positive_button:
				onCommitChoice();
				break;
			case R.id.negative_button:
				setResult(RESULT_CANCELED);
				finish();
				break;
		}
	}
	
	private void onCommitChoice() {
		int checkedItem = getListView().getCheckedItemPosition();
		int pickedResource = mAdapter.getItem(checkedItem);
		Intent resultData = new Intent();
		resultData.putExtra(EXTRA_PICKED_ICON, pickedResource);
		setResult(RESULT_OK, resultData);
		finish();
	}
}
